package cn.cosmosx.base.security.dynamic;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 动态权限处理管理器
 * <p>
 * {@link AccessDecisionManager} 的实现
 */
@Slf4j
@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 拿到 DynamicFilterInvocationSecurityMetadataSource 提供的角色拥有的权限资源
        final Set<String> resourcesByRoles = configAttributes.stream().map(ConfigAttribute::getAttribute).collect(Collectors.toSet());
        // 白名单放行
        if (resourcesByRoles.contains(DynamicFilterInvocationSecurityMetadataSource.ROLE_ANONYMOUS)) {
            return;
        }
        // 如果当前用户 Authentication 有 requestUrl 的权限, 则认证通过
        final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (resourcesByRoles.contains(grantedAuthority.getAuthority())) {
                log.info("{}#decide:authorize success.", this.getClass().getName());
                return;
            }
        }
        // 如果不执行 SecurityContextHolder.clearContext() 即使抛出 AccessDeniedException,
        // 最终 HttpSecurity#exceptionHandling()#accessDeniedHandler(CustomAccessDeniedHandler) 也会捕获到 AuthorizationServiceException
        SecurityContextHolder.clearContext();
        // 抛出异常 AuthorizationServiceException，
        // 交给CustomAccessDeniedHandler#handle(HttpServletRequest, HttpServletResponse, AccessDeniedException)捕获处理
        throw new AuthorizationServiceException("无权限访问");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        log.info("{}#supports:{}", this.getClass().getName(), clazz.getName());
        return true;
    }
}
